package TOP101;

import java.util.ArrayList;

/**
 * @Question BM5
 * @Date 2022/11/2 9:56
 * @Solution
 */
public class BM5 {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        return divideMerge(lists, 0, lists.size() - 1);
    }

    public ListNode Merge(ListNode list1, ListNode list2) {
        ListNode head = new ListNode(0);
        ListNode cur = head;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                ListNode node = new ListNode(list1.val);
                cur.next = node;
                cur = node;
                list1 = list1.next;
            } else {
                ListNode node = new ListNode(list2.val);
                cur.next = node;
                cur = node;
                list2 = list2.next;
            }
        }
        if (list1 != null) {
            cur.next = list1;
        }
        if (list2 != null) {
            cur.next = list2;
        }
        return head.next;
    }

    public ListNode divideMerge(ArrayList<ListNode> list, int left, int right) {
        if (left > right) {
            return null;
        }
        if (left == right) {
            return list.get(left);
        }
        int mid = (left + right) / 2;
        return Merge(divideMerge(list, left, mid), divideMerge(list, mid + 1, right));
    }
}
